GM.plwep = {}

function WSWeaponReceive(dat)
	local self = gmod.GetGamemode()
	local pl = dat:ReadEntity()
	local itclass = dat:ReadString()
	
	if itclass == "!none" or itclass == "" then
		if self.plwep[pl] then
			for k,v in ipairs(self.plwep[pl].dat) do
				if IsValid(v.ent) then
					v.ent:Remove()
				end
			end
		end
		self.plwep[pl] = nil
	else
		if not self.plwep[pl] then
			self.plwep[pl] = {}
		else
			for k,v in ipairs(self.plwep[pl].dat) do
				if IsValid(v.ent) then
					v.ent:Remove()
				end
			end
			self.plwep[pl] = {}
		end
		
		self.plwep[pl].wep = itclass
		self.plwep[pl].dat = {}
		
		local tab = self.items[itclass]
		if tab then
			for k,v in pairs(tab.viewmodel or {}) do
				local out = {}
				out.ent = ClientsideModel(v.model or "models/Weapons/w_bugbait.mdl")
				out.ent:DrawShadow(true)
				out.ent:SetModelScale(v.size or Vector(1,1,1))
				out.ent:SetupBones()
				
				if v.color then
					out.ent:SetRenderMode(v.rendermode or RENDERMODE_TRANSTEXTURE)
					local c = v.color
					out.ent:SetColor(c)
				elseif v.rendermode then
					out.ent:SetRenderMode(v.rendermode)
				end
				if v.material then
					out.ent:SetMaterial(v.material)
				end
				
				for i,o in pairs(v) do
					out[i] = o
				end
				
				table.insert(self.plwep[pl].dat,out)
			end
		end
		
		/*
		Structure:
		self.plwep[pl]
			wep = strClass
			dat = {
				1 = {
					ent = entClientsideModel
					bone = strBone
					size = vecSize
					pos = vecPos
					ang = angAng
				}
			}
		*/
	end
end

usermessage.Hook("wsWeapon",WSWeaponReceive)

local renderSceneClearColor = Color( 255,255,255,0 )
function GM:RenderScene(ViewOrigin,ViewAngles)
	local self = gmod.GetGamemode()
	for pl,tab in pairs(self.plwep) do
		if IsValid(pl) and pl:Alive() then //If they are dead, they are not the actual ragdoll
			local bonepos = {}
			local boneang = {}
			for k,v in pairs(tab.dat) do
				local bone = v.bone
				local pos = bonepos[bone]
				local ang = boneang[bone]
				if not pos then
					boneindex = pl:LookupBone(bone)
					pos,ang = pl:GetBonePosition(boneindex)
					bonepos[bone] = pos
					boneang[bone] = ang
				end
				pos = pos*1
				ang = ang*1
				
				local offpos = v.pos*1
				offpos:Rotate(ang)
				pos = pos + offpos
				
				local offang = v.ang*1
				local tang = ang*1 //So we don't get gimbal lock
				ang:RotateAroundAxis(tang:Right(),offang.p)
				ang:RotateAroundAxis(tang:Up(),offang.y)
				ang:RotateAroundAxis(tang:Forward(),offang.r)
				
				v.ent:SetPos(pos)
				v.ent:SetAngles(ang)
				if v.req && !(self:Has( v.req )) then
					v.ent:SetColor(renderSceneClearColor)
				elseif v.req then
					v.ent:SetColor(v.color)
				end
			end
		end
	end
end

